package com.wqc.count;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 限流 -- 固定窗口计数法
 * 在固定的时间内可以接受多少个请求
 * Dubbo就是采用类似的方法来限流
 */

public class TimeCountRateLimiter {

    private static AtomicInteger count = new AtomicInteger(0);

    private long refreshTime = System.currentTimeMillis();

    private int tps = 2; // 并发为5

    private int interval = 5; // 5毫秒时间内

    public void exec() {
        long now = System.currentTimeMillis();
        if (interval < now - refreshTime ) {
            refreshTime = now;
            count = new AtomicInteger(0);
        }
        if (count.get() >= tps) {
            System.out.println("请求用户过多，请稍后在试！" + System.currentTimeMillis() / 1000);
        } else {
            count.incrementAndGet();
            try {
                System.out.println("业务开始处理");
                //处理核心逻辑
                TimeUnit.SECONDS.sleep(1);
                System.out.println("业务处理完成: " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                count.decrementAndGet();
            }
        }
    }
}
